package com.lti.appnet.mongodb.aop;

import java.util.Collection;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lti.appnet.mongodb.domain.BaseDomain;
import com.lti.appnet.mongodb.event.IdIncrementEvent;

@Aspect
@Component
public class MongoDBIdAOP {
	@Autowired
	private IdIncrementEvent incrementEvent;

	// @Pointcut("execution(@com.pada.pet.configuration.AppController * *(..))")
	@Pointcut("execution(* org.springframework.data.mongodb.repository.MongoRepository.save(..))")
	public void dBIdCutPoint() {
	}

	@Around(value = "dBIdCutPoint()")
	public Object pointCut(ProceedingJoinPoint joinPoint) throws Throwable {
		Object object = joinPoint.getArgs()[0];
		if (object instanceof Collection) {
			Iterable<?> iterable = (Iterable<?>) object;
			for (Object _o : iterable) {
				if (_o instanceof BaseDomain) {
					setId((BaseDomain)_o);
					updateUCDate((BaseDomain)_o);
				}
			}
		}else{
			if(object instanceof BaseDomain){
				setId((BaseDomain)object);
				updateUCDate((BaseDomain)object);
			}
		}
		return joinPoint.proceed();
	}
	private synchronized  void setId(BaseDomain baseDomain) {
		incrementEvent.incrementIdSetting(baseDomain);
	}
	
	private void updateUCDate(BaseDomain baseDomain){
		baseDomain.setUcDate(new Date());
	}
}
